// pages/listing/listing.js
var count_down = require('../../utils/countDown.js');
var util = require('../../utils/util.js');
var regexp = require('../../utils/regexpUtil.js');
var pay = require('../../utils/pay.js');
var calc = require('../../utils/calc.js');
var kLine = require('../../component/kLine/kLine.js');
var listingapi = require('../../component/service/listingapi.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: getApp().globalData.host,
    listingId: '',
    listing: {},
    listings:{},
    sku:{},
    currentGroup:{},
    countDown: {},
    market: {},
    showTab: 'desc',
    quotes: [],
    quoteAmount: 0,
    isOpen: true,
    images:[],
    isShared:false,    
    quoteData: {
      canvasIndex: 1
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(typeof(options.isShared)!='undefined')
      this.data.isShared = options.isShared;
    that.setData({
      listingId: options.listingId,
      isShared:this.data.isShared
    })
    this.getListing();
    this.quoteLogs(this.data.listingId);
  },
  getListing:function(){
    let that = this;
    wx.request({
      url: that.data.host + 'webapp/listing/' + that.data.listingId + '.html',
      header: getApp().globalData.header,
      success: function (res) {
        var resData = res.data;
        resData.validTime = util.formatDate(resData.validTime);
        resData.expireTime = util.formatDate(resData.expireTime);
        /**
        var reg = /\[(\d+)\]/;
        if (resData.group.hasOwnProperty('$ref')) {//处理循环引用group
          if (reg.test(resData.group['$ref'])) { 
            resData.group = resData['allListings'][RegExp.$1]['group'];
          }
        }
        for (var i = 0; i < resData.allListings.length; i++) {//处理循环引用listings
          
          if (resData.allListings[i].hasOwnProperty('$ref')) {
            if (reg.test(resData.allListings[i]['$ref'])) {
              var flag = resData.allListings[i]['$ref'].split(/\[(\d+)\]/);
              resData.allListings[i] = resData.allListings[flag[1]].group.listings[flag[3]];
            }
          }
          //处理批次时间
          resData.allListings[i].validTime = util.formatDate(resData.allListings[i].validTime);
        }
        **/
        resData.group.desc = regexp.regexpImg(resData.group.desc);
        //设置出价初始价
        let startAmount = resData.currentAmount + resData.buyerIncrement;
        if(startAmount>resData.maxAmount){
          startAmount = resData.maxAmount;
        }
        resData.quoteAmount = startAmount;
        resData.price =  (resData.currentAmount / resData.quantity).toFixed(2);
        //count_down.countDown('',resData.expireTime,that,resData.listingCode);
        that.setData({
          listing: resData,
          quoteAmount: resData.quoteAmount
        });
        count_down.countDownSecond(resData.countdown, that, resData.listingCode);
        listingapi.getListings(resData.groupId,function(res){
          that.setData({
            listings:res
          })
        });
        listingapi.getSku(resData.group.skuId,function(res){
          that.setData({
            sku:res
          })
        });
        listingapi.getCurrentGroup(resData.groupId,function(res){
          that.setData({
            currentGroup:res
          })
        });
      },
      complete:function(res){
        that.getMarket();
        that.listingImages();
      }
    })
  },
  getMarket: function () {
    var that = this;
    wx.request({
      url: that.data.host + 'webapp/business/getMarket.html?marketId=' + that.data.listing.marketId,
      header: getApp().globalData.header,
      success: function (res) {
        var resData = res.data;
        resData.openTimeAM = util.formatSqlTime(resData.openTimeAM);
        resData.closeTimeAM = util.formatSqlTime(resData.closeTimeAM);
        resData.openTimePM = util.formatSqlTime(resData.openTimePM);
        resData.closeTimePM = util.formatSqlTime(resData.closeTimePM);
        that.setData({
          market: resData
        });
      }
    })
  },
  quoteLogs: function (listingId) {
    var that = this;
    wx.request({
      url: that.data.host + 'webapp/listing/quoteLogs.html?listingId=' + listingId,
      header: getApp().globalData.header,
      success: function (res) {
        if (typeof (res.data) == 'undefined' || res.data.length < 1) return;
        for (var i = 0; i < res.data.length; i++) {
          res.data[i].createTime = util.formatTimeStamp(res.data[i].createTime);
        }
        that.setData({
          quotes: res.data
        });
      }
    })
  },
  //获取挂牌SKU图片
  listingImages: function () {
    var that = this;
    wx.request({
      url: getApp().globalData.host + '/webapp/resource/skuImages.html?skuId=' + that.data.listing.group.skuId,
      header: getApp().globalData.header,
      success: function (res) {
        if (typeof (res.data) != 'undefined' && res.data.length > 0) {
          that.setData({
            images: res.data
          })
        }
      }
    })
  },
  countDownFinish: function (listingCode) {//休市处理函数
    this.setData({
      isOpen: false
    });
  },
  showDesc: function () {
    this.setData({
      showTab: 'desc'
    });
  },
  showGroup: function () {
    this.setData({
      showTab: 'group'
    });
  },
  showRecord: function () {
    this.setData({
      showTab: 'record'
    });
  },
  showInstruction: function () {
    this.setData({
      showTab: 'instruction'
    });
  },
  doMargin: function () {
    var that = this;
    if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
      wx.navigateTo({
        url: '../login/login'
      });
    } else {
      if (!this.data.isOpen) {
        wx.showModal({
          title: '提示',
          content:'已休市，请注意市场开放时间。',
          showCancel:false
        });
        return;
      }
      wx.showModal({
        title: '缴纳保证金：' + that.data.listing.buyerTransactionMarginAmount + '元',
        content: '若未摘牌，保证金自动退回；\r\n若摘牌成功，保证金转为货款，您需要支付剩余货款。\r\n点击[确认]视为理解并同意挂牌出价协议。',
        success: function (res) {
          if (res.confirm) {
            wx.request({
              url: getApp().globalData.host + 'webapp/listing/doMargin.html',
              header: getApp().globalData.header,
              method: 'POST',
              data: { listingId: that.data.listingId },
              success: function (res) {
                if (typeof (res.data) != 'undefined' && typeof (res.data.orderId) != 'undefined')
                  pay.specialPay(res.data);
                else {
                  wx.showModal({
                    title: '错误',
                    content:res.data.errorMsg,
                    showCancel:false
                  });
                }
              },
              fail: function (res) { },
              complete: function (res) { }
            })

          } else if (res.cancel) {//do nothing

          }
        }
      })
    }

  },
  //按钮减少出价，最低价不得低于当前价+加价幅度，每次减少加价幅度 最高出价不得超过maxAmount
  reduce: function () {
    var changeQuote = calc.sub(this.data.quoteAmount,this.data.listing.buyerIncrement);
    if (changeQuote >= this.data.listing.quoteAmount) {
      this.data.quoteAmount = changeQuote;
    } else {
      this.data.quoteAmount = this.data.listing.quoteAmount;
    }
    this.setData({
      quoteAmount: this.data.quoteAmount
    });
  },
  //按钮加价，按当前价+加价幅度
  add: function () {
    let changeQuote = calc.add(this.data.quoteAmount + this.data.listing.buyerIncrement);
    if(changeQuote>this.data.listing.maxAmount)
        changeQuote = this.data.listing.maxAmount;
    this.setData({
      quoteAmount: changeQuote
    });
  },
  //手动修改出价金额 ，最低价不得低于当前价+加价幅度 ，最高出价不得超过maxAmount
  quoteChange: function (e) {
    var reg = /^[1-9]+[0-9]*]*$/; //判断正整数
    var changeQuote = e.detail.value;
    if (reg.test(changeQuote)) {
      changeQuote = parseInt(changeQuote);
      if (changeQuote < this.data.listing.quoteAmount)
        changeQuote = this.data.listing.quoteAmount;
      if(changeQuote>this.data.listing.maxAmount)
        changeQuote = this.data.listing.maxAmount;
      this.setData({
        quoteAmount: changeQuote
      });
    } else {
      this.setData({
        quoteAmount: this.data.quoteAmount
      });
    }
  },
  doQuote: function () {
    var that = this;
    if (!this.data.isOpen) {
      wx.showModal({
        title: '提示',
        content:'已休市，请注意市场开放时间。',
        showCancel:false
      });
      return;
    }
    wx.showModal({
      title: '您的出价金额为：' + that.data.quoteAmount + '元',
      content: '若您竞价成功\r\n需要支付 [出价金额] 扣除 [保证金] 之后的剩余货款；\r\n如未支付，您缴纳的保证金将赔付给送拍方。',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: getApp().globalData.host + 'webapp/listing/doQuote.html',
            header: getApp().globalData.header,
            method: 'POST',
            data: { listingId: that.data.listingId, quoteAmount: that.data.quoteAmount },
            success: function (res) {
              if (typeof (res.data) != 'undefined' && res.data.errorCode == 0) {//创建记录成功
                wx.showToast({
                  title: '出价成功',
                  icon: 'success',
                  duration: 2000
                });
                //重新加载出价记录以及当前listing信息
                that.getListing();
                that.quoteLogs(that.data.listingId);
              } else {
                wx.showModal({
                  title: '错误',
                  content:res.data.errorMsg,
                  showCancel:false
                });
              }
            },
            fail: function (res) { },
            complete: function (res) { }
          })

        } else if (res.cancel) {//do nothing

        }
      }
    })
  },
  showNotice:function(){
    wx.navigateTo({
      url: '../notice/notice?groupId=' + this.data.listing.groupId,
    })
  },
  //分享该页面
  onShareAppMessage: function () {
    return {
      title: '[分享挂牌]' + this.data.listing.listingName,
      path: '/pages/listing/listing?isShared=true&listingId=' + this.data.listingId
    }
  },
  //返回首页（分享页面时，后退无用）
  goHome:function(){
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})